package com.yc.book.servlet;

import com.google.gson.Gson;

import com.yc.book.vo.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet({"/images"})
//指定该servlet支持文件上传
//location：上传文件的保存目录
//maxFileSize：单个文件的最大大小
//maxRequestSize：整个请求的最大大小
//fileSizeThreshold：超过该大小的文件会被写入磁盘，否则保存在内存中
//单位都是字节
//注意：如果不指定这些参数，那么默认值都是-1，即不限制
@MultipartConfig(maxFileSize =  1024 * 1024 ,
                    maxRequestSize = 1024 * 1024 * 10,
                    fileSizeThreshold = 1024 * 1024 * 5)
public class UploadServlet extends HttpServlet {
        //上传文件的保存目录
        private String uploadDir = "E:/PX_code/二期/bookdemo1/src/main/webapp/images";

        public String getUploadDir(){
            return uploadDir;
        }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Gson gson = new Gson();
        //获取上传的文件
        try {
            Part part = req.getPart("file");
            String fileName = part.getSubmittedFileName();
//            String prefix = fileName.substring(0, fileName.lastIndexOf("."));  前缀
            String suffix  = fileName.substring(fileName.lastIndexOf("."));  //后缀
            //生成随机前缀名 UUID
            String prifix = UUID.randomUUID().toString().replaceAll("-","");
            fileName = prifix+suffix;
            //File.separator  文件分隔符
            String filePath = uploadDir +File.separator +  fileName;
            File file = new File(filePath);

            resp.setContentType("application/json;charset=utf-8");
           /* if (file.exists()) {
                gson.toJson(new Result(0,"文件已存在",null),resp.getWriter());
                return;
            }
*/
            //保存文件
            part.write(filePath);
            gson.toJson(new Result(1,"文件上传成功",fileName),resp.getWriter());
         }catch (Exception e) {
            e.printStackTrace();
            gson.toJson(new Result(-1,"文件上传失败",null),resp.getWriter());
        }
    }

    @Override
    public void init() throws ServletException {
        //创建上传文件的保存路径
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();//创建多级目录
            //dir.mkdir()  创建单机目录
          }
    }
}
